<template>
  <div class="container">
    <h2>申请停诊管理</h2>

    <el-form :model="form" label-width="120px" style="margin-top: 120px">
      <el-form-item label="选择排班">
        <el-select v-model="form.schedulingId" placeholder="请选择排班">
          <el-option
              v-for="item in schedules"
              :key="item.id"
              :label="`${formatDate(item.date)} ${formatTime(item.starttime)}-${formatTime(item.endtime)} (${item.clinic?.name || '无诊所'})`"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="停诊原因">
        <el-input
            v-model="form.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入停诊原因"
            maxlength="500"
            show-word-limit
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitApplication">提交申请</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const form = ref({
  schedulingId: '',
  reason: ''
})

const schedules = ref([])
const did = ref(null) // 应从登录信息获取

onMounted(() => {
  // 从sessionStorage获取医生ID
  const user = JSON.parse(sessionStorage.getItem('user'))
  did.value = user.id

  // 获取医生的排班
  fetchSchedules()
})

const fetchSchedules = () => {
  axios.get('/scheduling/selByDoc', {
    params: { did: did.value }
  }).then(res => {
    if (res.data.code === 200) {
      schedules.value = res.data.data
      console.log("111"+JSON.stringify(schedules.value))
    }
  })
}

const formatDate = (dateStr) => {
  if (!dateStr) return '无日期'
  return dateStr // 直接返回 YYYY-MM-DD 格式
}

const formatTime = (timeStr) => {
  if (!timeStr) return '无时间';

  // 如果已经是HH:mm格式
  if (/^\d{2}:\d{2}$/.test(timeStr)) {
    return timeStr;
  }

  // 如果是HH:mm:ss格式
  if (/^\d{2}:\d{2}:\d{2}$/.test(timeStr)) {
    return timeStr.substring(0, 5);
  }

  // 如果是YYYY-MM-DD HH:mm:ss格式
  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(timeStr)) {
    return timeStr.split(' ')[1].substring(0, 5);
  }

  return '无时间';
}

const submitApplication = () => {
  if (!form.value.schedulingId) {
    return ElMessage.warning('请选择排班')
  }
  if (!form.value.reason.trim()) {
    return ElMessage.warning('请输入停诊原因')
  }

  // 格式化当前时间为YYYY-MM-DD HH:mm:ss
  const formatDateTime = (date) => {
    const pad = num => num.toString().padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ` +
        `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
  }

  axios.post('/closeApply/add', {
    schedulingId: form.value.schedulingId,
    desc: form.value.reason,
    time: formatDateTime(new Date()),
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('停诊申请已提交')
      form.value = { schedulingId: '', reason: '' }
    }
  }).catch(err => {
    ElMessage.error('提交失败')
    console.error(err)
  })
}
</script>

<style scoped>
.container {
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}
</style>